import logging
import os
from logging.handlers import RotatingFileHandler

# 绑定到logger对象
logger = logging.getLogger(__name__)
root_path = os.path.dirname(os.path.abspath(__file__))
log_dir_path = os.path.join(root_path, '..', 'logs')
if not os.path.isdir(log_dir_path):
    os.makedirs(log_dir_path)

# file_handler：日志文件处理器，每个日志的大小、保存日志的上限
file_handler = RotatingFileHandler(
    os.path.join(log_dir_path, 'log.txt'), maxBytes=1024 * 1024, backupCount=10,
    encoding='utf-8'
)
date_string = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(
    '[%(asctime)s] %(levelname)s '
    '(filename)s/[line: %(lineno)d]/%(funcName)s % (message)s',
    datefmt=date_string
)

# 日志输出控制台的句柄
stream_handler = logging.StreamHandler()
file_handler.setFormatter(formatter)
stream_handler.setFormatter(formatter)
# 为全局的日志工具对象添加日志记录器
logger.addHandler(file_handler)
logger.addHandler(stream_handler)
# 设置日志级别
logger.setLevel(level=logging.INFO)